package chagine.core.aspect;

import chagine.core.annotation.CalculateTime;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 计算接口运行时间
 */
@Slf4j
@Aspect
@Component
public class InterfaceTimeAspect {

    @Pointcut("@annotation(chagine.core.annotation.CalculateTime)")
    public void calculateInterfaceTime() {
    }

    @Around("calculateInterfaceTime()")
    public Object pointcut(ProceedingJoinPoint point) throws Throwable {
        log.info("calculate interfaceTime...");

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Class declaringType = signature.getDeclaringType();
        CalculateTime calculateTime = AnnotationUtils.findAnnotation(method, CalculateTime.class);

        if(calculateTime == null){
            return point.proceed();
        }

        long begin = System.currentTimeMillis();
        try {
            return point.proceed();
        }
        catch (Exception e){throw e;}
        finally {
            long executeTime = System.currentTimeMillis() - begin;
            if(executeTime > calculateTime.timeout()){
                log.info(declaringType.getSimpleName() + "."+ method.getName() + "()运行时间:" + executeTime + "ms");
            }
        }

    }
}
